package com.linkage.educloud.ah.http;

import android.text.TextUtils;
import android.util.Log;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.config.AccountConfig;
import com.zhouyou.http.interceptor.BaseDynamicInterceptor;
import com.zzhou.common.library.util.C;
import com.zzhou.common.library.util.FormatUtils;
import com.zzhou.common.library.util.NativeHelper;
import com.zzhou.common.library.util.SystemTool;
import com.zzhou.common.library.util.Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.TreeMap;

import static com.zhouyou.http.utils.HttpUtil.UTF8;

/**
 * <desc>
 * Created by The Moss on 2018/8/6.
 */

public class CustomSignInterceptorNew extends BaseDynamicInterceptor<CustomSignInterceptorNew> {

    public TreeMap<String, String> dynamic(TreeMap<String, String> dynamicMap) {
//        if (isTimeStamp()) {//是否添加时间戳，因为你的字段key可能不是timestamp,这种动态的自己处理
//            dynamicMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
//        }

        for (Map.Entry<String, String> entry : dynamicMap.entrySet()) {
            String urlValue = null;
            try {
                urlValue = URLDecoder.decode(entry.getValue(), UTF8.name());
                dynamicMap.put(entry.getKey(), urlValue);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        StringBuilder sb = new StringBuilder();
        if (isAccessToken()) {//是否添加token
            String accessToken = AccountConfig.getLoginAccount().getToken();
            if (TextUtils.isEmpty(accessToken)) {
                throw new IllegalStateException("need an accessToken, but now is null");
            }
            sb.append(accessToken);
        }
        sb.append(",");
        sb.append(FormatUtils.formatNow(null));
        sb.append(",");
        sb.append(Utils.randomLong());
//        String extend = URLEncoder.encode(URLEncoder.encode(NativeHelper.encrypt(sb.toString())));
        String extend = NativeHelper.newEncrypt(sb.toString());
        dynamicMap.put("extend", extend);
        dynamicMap.put("origin", Constants.DEVICE + "," + SystemTool.getAppVersionName(MyApplication.getInstance()));
//        if (isSign()) {//是否签名
            //1.因为你的字段key可能不是sign，这种需要动态的自己处理
            //2.因为你的签名的规则不一样，签名加密方式也不一样，只提供自己能够扩展的能力
            dynamicMap.put("sig", C.getSig(dynamicMap));
//        }
        for (Object key : dynamicMap.keySet()) {
            Log.e("WDJsonObjectRequest", key + ":" + dynamicMap.get(key) + "\n");
        }
        return dynamicMap;
    }
}
